package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.ocr

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaProofOcrBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.idcarddoing.IdcardGhanaDoingActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.subview.IProofGhanaPhotoPickerListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.subview.ProofGhanaPhotoPicker
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class ProofGhanaOcrActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var proofOcrViewModel: ProofGhanaOcrViewModel
    private lateinit var binding: ActivityGhanaProofOcrBinding
    private lateinit var imagePicker: ProofGhanaPhotoPicker
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        proofOcrViewModel = ViewModelProvider(this)[ProofGhanaOcrViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaProofOcrBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val save = binding.save
        val loading = binding.loading

        imagePicker = ProofGhanaPhotoPicker(object : IProofGhanaPhotoPickerListener {
            override fun onClick(type: Int) {
                if (0 == type) {
                    // take picture
                    val intent =
                        Intent(this@ProofGhanaOcrActivity, IdcardGhanaDoingActivity::class.java)
                    startActivityForResult(intent, REQUEST_CODE_ACTIVITY_OCR_DOING)
                } else {
                    // ablum
                    pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                }
            }
        })

        // 页面loading状态接口监听
        proofOcrViewModel.loadingResult.observe(this@ProofGhanaOcrActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面UI状态接口监听
        proofOcrViewModel.pageDetailResult.observe(this@ProofGhanaOcrActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            selectType(
                pageDetailResult.type,
                pageDetailResult.frontPicBitmap,
                pageDetailResult.backPicBitmap
            )
        })

        // 流程接口监听
        proofOcrViewModel.mainProcessResult.observe(this@ProofGhanaOcrActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                proofOcrViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        proofOcrViewModel.nextRouterResult.observe(this@ProofGhanaOcrActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 跳转相册监听
        pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    proofOcrViewModel.handlePickImageResult(
                        this@ProofGhanaOcrActivity,
                        uri
                    )
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        // 点击保存
        save.setOnClickListener {
            loading.visibility = View.VISIBLE
            proofOcrViewModel.saveOcrInfo()
            hitPoint("PROOF_OCR_COMMIT")
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击idcard
        binding.idcardBg.setOnClickListener {
            proofOcrViewModel.selectType(0)

            hitPoint("PROOF_IDCARD_TYPE_CLICK")
        }
        binding.idcardPickFrontIcon.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            proofOcrViewModel.isPickFront = true
            imagePicker.showNow(supportFragmentManager, "idcardPickFrontIcon")

            hitPoint("PROOF_IDCARD_FRONT_CLICK")
        }
        binding.idcardPickBackIcon.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            proofOcrViewModel.isPickFront = false
            imagePicker.showNow(supportFragmentManager, "idcardPickBackIcon")

            hitPoint("PROOF_IDCARD_BACK_CLICK")
        }

        // 点击drving
        binding.drvingBg.setOnClickListener {
            proofOcrViewModel.selectType(1)

            hitPoint("PROOF_DRVING_TYPE_CLICK")
        }
        binding.drvingPickFrontIcon.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            proofOcrViewModel.isPickFront = true
            imagePicker.showNow(supportFragmentManager, "drvingPickFrontIcon")

            hitPoint("PROOF_DRVING_FRONT_CLICK")
        }
        binding.drvingPickBackIcon.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            proofOcrViewModel.isPickFront = false
            imagePicker.showNow(supportFragmentManager, "drvingPickBackIcon")

            hitPoint("PROOF_DRVING_BACK_CLICK")
        }

        // 点击passport
        binding.passportBg.setOnClickListener {
            proofOcrViewModel.selectType(2)

            hitPoint("PROOF_PASSPORT_TYPE_CLICK")
        }
        binding.passportPickFrontIcon.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            proofOcrViewModel.isPickFront = true
            imagePicker.showNow(supportFragmentManager, "passportPickFrontIcon")

            hitPoint("PROOF_PASSPORT_FRONT_CLICK")
        }

        // 初始化页面
        proofOcrViewModel.selectType(0)
    }

    /**
     * 更新类型选择UI
     */
    private fun selectType(type: Int = 0, frontBitmap: Bitmap? = null, backBitmap: Bitmap? = null) {
        when (type) {
            0 -> {
                binding.idcardBg.setBackgroundResource(R.drawable.bg_proof_ocr_doc_checked)
                binding.idcardIcon.setImageResource(R.drawable.pic_proof_idcard_hl)
                binding.idcardTitle.setTextColor(Color.parseColor("#5277D6"))
                binding.idcardCheckbox.setImageResource(R.drawable.pic_proof_checked)

                binding.drvingBg.setBackgroundResource(R.drawable.bg_white_cor_12dp)
                binding.drvingIcon.setImageResource(R.drawable.pic_proof_drving_nor)
                binding.drvingTitle.setTextColor(Color.parseColor("#999999"))
                binding.drvingCheckbox.setImageResource(R.drawable.pic_proof_uncheck)

                binding.passportBg.setBackgroundResource(R.drawable.bg_white_cor_12dp)
                binding.passportIcon.setImageResource(R.drawable.pic_proof_passport_nor)
                binding.passportTitle.setTextColor(Color.parseColor("#999999"))
                binding.passportCheckbox.setImageResource(R.drawable.pic_proof_uncheck)

                binding.idcardPickBg.visibility = View.VISIBLE
                binding.drvingPickBg.visibility = View.GONE
                binding.passportPickBg.visibility = View.GONE

                // 更新占位图
                if (frontBitmap != null) {
                    binding.idcardPickFrontIcon.setImageBitmap(frontBitmap)
                } else {
                    binding.idcardPickFrontIcon.setImageResource(R.drawable.pic_proof_idcard_pick_front)
                }

                if (backBitmap != null) {
                    binding.idcardPickBackIcon.setImageBitmap(backBitmap)
                } else {
                    binding.idcardPickBackIcon.setImageResource(R.drawable.pic_proof_idcard_pick_back)
                }
            }

            1 -> {
                binding.idcardBg.setBackgroundResource(R.drawable.bg_white_cor_12dp)
                binding.idcardIcon.setImageResource(R.drawable.pic_proof_idcard_nor)
                binding.idcardTitle.setTextColor(Color.parseColor("#999999"))
                binding.idcardCheckbox.setImageResource(R.drawable.pic_proof_uncheck)

                binding.drvingBg.setBackgroundResource(R.drawable.bg_proof_ocr_doc_checked)
                binding.drvingIcon.setImageResource(R.drawable.pic_proof_drving_hl)
                binding.drvingTitle.setTextColor(Color.parseColor("#5277D6"))
                binding.drvingCheckbox.setImageResource(R.drawable.pic_proof_checked)

                binding.passportBg.setBackgroundResource(R.drawable.bg_white_cor_12dp)
                binding.passportIcon.setImageResource(R.drawable.pic_proof_passport_nor)
                binding.passportTitle.setTextColor(Color.parseColor("#999999"))
                binding.passportCheckbox.setImageResource(R.drawable.pic_proof_uncheck)

                binding.idcardPickBg.visibility = View.GONE
                binding.drvingPickBg.visibility = View.VISIBLE
                binding.passportPickBg.visibility = View.GONE

                // 更新占位图
                if (frontBitmap != null) {
                    binding.drvingPickFrontIcon.setImageBitmap(frontBitmap)
                } else {
                    binding.drvingPickFrontIcon.setImageResource(R.drawable.pic_proof_idcard_pick_front)
                }

                if (backBitmap != null) {
                    binding.drvingPickBackIcon.setImageBitmap(backBitmap)
                } else {
                    binding.drvingPickBackIcon.setImageResource(R.drawable.pic_proof_idcard_pick_back)
                }
            }

            2 -> {
                binding.idcardBg.setBackgroundResource(R.drawable.bg_white_cor_12dp)
                binding.idcardIcon.setImageResource(R.drawable.pic_proof_idcard_nor)
                binding.idcardTitle.setTextColor(Color.parseColor("#999999"))
                binding.idcardCheckbox.setImageResource(R.drawable.pic_proof_uncheck)

                binding.drvingBg.setBackgroundResource(R.drawable.bg_white_cor_12dp)
                binding.drvingIcon.setImageResource(R.drawable.pic_proof_drving_hl)
                binding.drvingTitle.setTextColor(Color.parseColor("#999999"))
                binding.drvingCheckbox.setImageResource(R.drawable.pic_proof_uncheck)

                binding.passportBg.setBackgroundResource(R.drawable.bg_proof_ocr_doc_checked)
                binding.passportIcon.setImageResource(R.drawable.pic_proof_passport_hl)
                binding.passportTitle.setTextColor(Color.parseColor("#5277D6"))
                binding.passportCheckbox.setImageResource(R.drawable.pic_proof_checked)

                binding.idcardPickBg.visibility = View.GONE
                binding.drvingPickBg.visibility = View.GONE
                binding.passportPickBg.visibility = View.VISIBLE

                // 更新占位图
                if (frontBitmap != null) {
                    binding.passportPickFrontIcon.setImageBitmap(frontBitmap)
                } else {
                    binding.passportPickFrontIcon.setImageResource(R.drawable.pic_proof_idcard_pick_front)
                }
            }
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        val list = mutableListOf(android.Manifest.permission.CAMERA)
        if (checkPermissionsGranted(list)) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            "App will request Camera Permission",
            100,
            *(list.toTypedArray())
        )
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askCameraPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        } else if (requestCode == REQUEST_CODE_ACTIVITY_OCR_DOING) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("imageOutputPath")
                // 更新页面
                proofOcrViewModel.handleTakePictureResult(imageOutputPath)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}